/*
 * Universial Enterprise Authenticate And Authority Center
 * 
 * Copyright(c) 2005 SunRise Inc. Ricsson Group All rights reserved.
 * 
 * @created: 2005-06-21 @author: Andy
 */

package com.mindao.app.weixin.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.mindao.app.weixin.conf.WxmpAccount;
import com.mindao.app.weixin.utils.WeixinConstants;
import com.mindao.utils.config.EaCommonUtils;

@Component("wxmpAuthInterceptor")
public class WxmpAuthInterceptor extends HandlerInterceptorAdapter { 
	private final Logger log = LoggerFactory.getLogger(WxmpAuthInterceptor.class);
	@Autowired
	private WxmpAccount wxmpAccount;
    /**
     * 微信地址访问拦截器
     */
    @Override    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {    
        String openid =  (String)request.getSession().getAttribute(WeixinConstants.SESSION_OPENID);   
        if(openid == null){  
        	log.info("111111111111111111");
            //log.info("SecurityInterceptor：跳转到login页面！");//+":"+request.getServerPort()
        	String currentUrl=EaCommonUtils.getRequestUrl(request);
        	log.info("currentUrl"+currentUrl);
        	//假设只有一个参数,eventState为对应uuid
        	Map<String,String> paramMap= EaCommonUtils.requestParamToMap(request);
        	String eventState=null;
        	for (java.util.Map.Entry enry:paramMap.entrySet()){
        		log.info("key" +enry.getKey());
        		eventState=(String)enry.getValue();
        		log.info("eventState:"+eventState);
        	}
        	String authUrl=currentUrl.replace("Wxmp.do", "WxmpAuth.do");
        	log.info("authUrl:"+authUrl);
    		String redirectUrl=SnsAccessTokenApi.getAuthorizeURL(wxmpAccount.getWxAppId(),  authUrl,  false,eventState);
    		log.info("redirectUrl:"+redirectUrl);

            response.sendRedirect(redirectUrl);
            return false;  
        }
        return true;
    }
		
  } 